package cn.jx.cjm.security.common.util;

import org.springframework.stereotype.Component;
import cn.jx.cjm.security.common.config.ResponseHeadersProperties;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author James Chen right_way@foxmail.com
 * @since 2020/9/25 3:30 下午
 */
@Component
public class ResponseUtils {

    @Autowired
    private ResponseHeadersProperties responseHeadersProperties;

    public void send(HttpServletRequest request, HttpServletResponse response, String obj) throws IOException {
        confirm(request, response);
        response.getWriter().write(obj);
    }

    public void confirm(HttpServletRequest request,HttpServletResponse response) {
        if (responseHeadersProperties.getAllowCross()) {
            response.setContentType("application/json;charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", responseHeadersProperties.getAllowOrigin());
            response.setHeader("Origin", request.getHeader("Origin"));
        }
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Methods", responseHeadersProperties.getAllowMethods());
        response.setHeader("Access-Control-Allow-Headers", responseHeadersProperties.getAllowHeaders());
        response.setHeader("Access-Control-Allow-Credentials", responseHeadersProperties.getAllowCredentials());
        response.setHeader("Access-Control-Expose-Headers", responseHeadersProperties.getExposeHeaders());
        response.setHeader("Access-Control-Request-Headers", responseHeadersProperties.getRequestHeaders());
        response.setHeader("Expires", responseHeadersProperties.getExpires() + "");
    }
}
